class UsersController < ApplicationController
  before_action only: [:update, :reset_password, :auto_login] do
    @user = Rails.cache.fetch(request.headers["token"])
    render json: Failure.new("您还未登录") if @user.blank?
  end

  def login
    user = User.registered.find_by(mobile: params[:mobile])
    if user.nil?
      render json: Failure.new("您的手机号还未注册")
    else
      encrypted_password = Digest::MD5.hexdigest("#{params[:password]}|#{user.salt}")
      if encrypted_password.eql?(user.password)
        user.update(device_type: params[:device_type], device_token: params[:device_token])
        Rails.cache.write(user.token, user)
        render json: Success.new(user: user)
      else
        render json: Failure.new('您输入的密码不正确')
      end
    end
  end


  def update
    if @user.update(update_params)
      render json: Success.new(user: @user)
    else
      render json: Failure.new(@user.errors.full_messages.join(";"))
    end
  end

  def reset_password
    if @user.update(reset_password_params)
      Rails.cache.write(@user.token, @user)
      render json: Success.new(user: @user)
    else
      render json: Failure.new(@user.errors.full_messages.join(";"))
    end
  end


  def auto_login
    render json: Success.new(user: @user)
  end

  protected
  def update_params
    params.permit(:avatar, :gender, :idCard, :career, :company)
  end

  def reset_password_params
    params.permit(:password, :new_password, :re_password)
  end
end
